package com.xmbandu.app.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.util.List;

public class AppInstallUtils {
    private static List<PackageInfo> cachedList;
    private static long lastDetectTime = 0;

    /**
     * 判断是否安装了微信
     */
    public static boolean isWeixinAvailable(Context context) {
        return isPackageAvailable(context, "com.tencent.mm");
    }

    /**
     * 判断淘宝是否安装
     * @param context
     * @return
     */
    public static boolean isTaoBaoAvailable(Context context) {
        return isPackageAvailable(context, "com.taobao.taobao");
    }

    /**
     * 判断qq是否可用
     */
    public static boolean isQQClientAvailable(Context context) {
        return isPackageAvailable(context, "com.tencent.mobileqq");
    }

    /**
     * 判断是否安装了微博
     */
    public static boolean isWeiboAvailable(Context context) {
        return isPackageAvailable(context, "com.sina.weibo");
    }

    /**
     * 判断是否安装了钉钉
     */
    public static boolean isDingDingAvailable(Context context) {
        return isPackageAvailable(context, "com.alibaba.android.rimet");
    }

    public static boolean isPackageAvailable(Context context, String pkgName) {
        List<PackageInfo> pinfo = getCachedList(context);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName.toLowerCase();
                if (pn.equals(pkgName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static List<PackageInfo> getCachedList(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        if (cachedList == null || cachedList.size() == 0 || System.currentTimeMillis() - lastDetectTime > 60000 * 5) {
            cachedList = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            lastDetectTime = System.currentTimeMillis();
        }
        return cachedList;
    }




}
